#include "TcpConnection.h"
#include <iostream>
#include <sstream>

TcpConnection::TcpConnection(int fd)
:_sockIO(fd)
,_sock(fd)
,_localAddr(getLocalAddr())
,_peerAddr(getPeerAddr())
{}

TcpConnection::~TcpConnection(){

}

string TcpConnection::receive(){
    char buff[65535] = {0};
    _sockIO.readLine(buff,sizeof(buff));

    return string(buff);
}

void TcpConnection::send(const string & msg){
    _sockIO.writen(msg.c_str(),msg.size());
}

string TcpConnection::toString(){
    ostringstream oss;
    oss << _localAddr.ip() << ":"
        << _localAddr.port() << "---->"
        << _peerAddr.ip() << ":"
        << _peerAddr.port();

    return oss.str();
}

InetAddress TcpConnection::getLocalAddr(){
    struct sockaddr_in addr;
    socklen_t len = sizeof(struct sockaddr);
    int ret = getsockname(_sock.fd(),(struct sockaddr *)&addr,&len);
    if(-1 == ret){
        perror("getsockname");
    }
    return InetAddress(addr);
}

InetAddress TcpConnection::getPeerAddr(){
    struct sockaddr_in addr;
    socklen_t len = sizeof(struct sockaddr);
    int ret = getpeername(_sock.fd(),(struct sockaddr*)&addr,&len);
    if(-1 == len){
        perror("getpeername");
    }

    return InetAddress(addr);
}
